package com.stu.wgt.test.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stu.wgt.test.bean.Order;
import com.stu.wgt.test.bean.Product;
import com.stu.wgt.test.bean.ProductCategories;
import com.stu.wgt.test.result.R;
import com.stu.wgt.test.result.ResultCodeEnum;
import com.stu.wgt.test.service.OrderService;
import com.stu.wgt.test.service.ProductCategoriesService;
import com.stu.wgt.test.service.ProductService;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgt
 * @since 2024-01-20
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    ProductService productService;

    @Autowired
    ProductCategoriesService CateService;


    /**
     * 增加订单
     *
     * @param orders 订单列表
     * @return 如果成功插入订单，则返回成功消息，否则返回失败消息
     */
    @Transactional(rollbackFor = Exception.class) // 指定回滚条件为Exception及其子类
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public R addOrder(@RequestBody List<Order> orders) {
        try {
            int result = 0;
            boolean re = false;
            // 设置回滚点
            Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
            for (Order order : orders) {
                // 判断库存是否充足
                re = orderService.checkNumber(order.getProductId(), order.getQuantity());
                if (!re) {
                    // 回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    return R.setResult(ResultCodeEnum.NOT_FOUND).data("msg", order.getProductName() + "库存不足");
                }
                // 添加订单
                result = orderService.insert(order);
                if (result == 0) {
                    // 抛出异常，进行回滚
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new RuntimeException("更新失败，库存不足1");
                }
                // 更新库存
                result = orderService.updateNumber(order.getProductId(), order.getQuantity());
                if (result == 0) {
                    // 抛出异常，进行回滚
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new RuntimeException("更新失败，库存不足2");
                }

            }
//            result =  orderService.insertOrderList(orders);
//            if(result == 0) {
//                throw new RuntimeException("库存不足");
//            }
            return R.ok().data("msg", "增加成功").data("order", orders);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().data("msg", "增加失败，库存不足");
        }
    }

    /**
     * 用户购买的商品是否小于库存
     * @param orders
     * @return
     */
    @RequestMapping(value = "/number", method = RequestMethod.POST)
    public R checkNumbers(@RequestBody List<Order> orders) {
        try {
            for (Order order : orders) {
                boolean relust = orderService.checkNumber(order.getProductId(), order.getQuantity());
                if (!relust) {
                    return R.setResult(ResultCodeEnum.NOT_FOUND).data("msg", order.getProductName() + "库存不足");
                }
            }
            return R.ok().data("msg", "库存充足");
        } catch (Exception e) {
            e.printStackTrace();
            return R.setResult(ResultCodeEnum.UNKNOWN_REASON);
        }
    }

    /**
     * 根据ID删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public R deleteOrder(@PathVariable("id") Integer id) {
        int result = orderService.delete(id);
        if (result == 1) {
            return R.ok().data("msg", "删除成功");
        }
        return R.error().data("msg", "删除失败");
    }

    /**
     * 根据ID更新
     *
     * @param orders
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public R updateOrder(@RequestBody List<Order> orders) {
        System.out.println(orders);
        try {
            for (Order order : orders) {
                orderService.update(order);
            }
            return R.ok().data("msg", "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().data("msg", "更新失败");
        }
    }

    /**
     * 根据ID查找
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/selectById/{id}", method = RequestMethod.GET)
    public R selectById(@PathVariable("id") Integer id) {
        List<Order> orderList = orderService.selectById(id);
        for (Order list : orderList) {
            System.out.println("循坏");
            List<Product> productList = productService.selectById(list.getProductId());
            System.out.println(productList + "/n");
            list.setProductName(productList.get(0).getName());
            list.setProductUrl(productList.get(0).getUrl());
        }
        if (!orderList.isEmpty()) {
            return R.ok().data("order", orderList);
        }
        return R.error().data("msg", "查找失败");
    }

    /**
     * 根据用户ID查询
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/selectByUserId/{id}", method = RequestMethod.GET)
    public R selectByUserId(@PathVariable("id") Integer userId) {
        System.out.println("循坏2");
        try {
            List<Order> orderList = orderService.selectByUserId(userId);
            for (Order list : orderList) {
                List<Product> productList = productService.selectById(list.getProductId());
                System.out.println(productList + "/n");
                list.setProductName(productList.get(0).getName());
                list.setProductUrl(productList.get(0).getUrl());
            }
            return R.ok().data("order", orderList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().data("msg", "参数错误");
        }
    }

    @RequestMapping(value = "/selectByUserIdAndStatus", method = RequestMethod.GET)
    public R selectByUserIdAndStatus(@RequestParam("userId") Integer userId, @RequestParam("status") String status) {
        try {
            List<Order> orderList = orderService.selectByUserIdAndStatus(userId, status);
            for (Order list : orderList) {
                System.out.println("循坏3");
                List<Product> productList = productService.selectById(list.getProductId());
                System.out.println(productList + "/n");
                list.setProductName(productList.get(0).getName());

                list.setProductUrl(productList.get(0).getUrl());
            }
            return R.ok().data("order", orderList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @RequestMapping(value = "/selectByStatus/{status}", method = RequestMethod.GET)
    public R selectByStatus(@PathVariable("status") String status) {
        try {
            List<Order> orderList = orderService.selectByStatus(status);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 分页查询
     *
     * @param
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public R selectOrder(
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "merchantId", required = false) Integer merchantId,
            @RequestParam(value = "pagenum") int pageNum,
            @RequestParam(value = "pagesize") int pageSize) {
        try {
            IPage<Order> orderIPage = orderService.search(userId, merchantId, status, pageNum, pageSize);
            List<Order> orders = orderIPage.getRecords();
            // 遍历订单，为每个订单添加产品信息
            for (Order order : orders) {
                List<Product> productList = productService.selectById(order.getProductId());
                if (!productList.isEmpty()) {
                    Product product = productList.get(0);
                    order.setProductName(product.getName());
                    order.setProductUrl(product.getUrl());
                }
            }
            return R.ok().data("order", orderIPage.getRecords()).data("total", orderIPage.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().data("msg", "查询失败");
        }
    }

    @RequestMapping(value = "/numberAndPrice", method = RequestMethod.GET)
    public R numberAndPrice() {
        try {
            List<Order> orderList = orderService.selectAll();
            int number = 0, price = 0; // 用来保存总销量和总的销售额
            for(Order order: orderList) {
                number += order.getQuantity();
                price += order.getPrice().doubleValue();
            }
            return R.ok().data("number", number).data("price", price);
        } catch (Exception e) {
            return R.error();
        }
    }

    @RequestMapping(value = "/echart", method = RequestMethod.GET)
    public R echarts() {
        Map<String, Object> result = new HashMap<>();
        List<ProductCategories> cates = CateService
                .searchProductCategories(1, 1, 10)
                .getRecords();
        String[] categories = new String[cates.size()];// 存储商品分类名称
        int i = 0;
        for(ProductCategories cate: cates) {
            categories[i] = cate.getName();
            i++;
        }
       // 获取商品分类销售数据
        int as[] = {1, 4, 8, 12, 16};
        int number[] = new int[as.length];
        int price[] = new int[as.length];
        for(int j = 0; j < as.length; j++) {
            number[j] = getCateNumber(as[j])[0];
            price[j] = getCateNumber(as[j])[1];
        }
        result.put("title", Collections.singletonMap("text", "各分类销售情况"));
        result.put("tooltip", Collections.singletonMap("trigger", "axis"));
        result.put("xAxis", Collections.singletonMap("data", categories));
        Map<String, Object> seriesData = new HashMap<>();
        seriesData.put("type", "bar");
        seriesData.put("name", "销售量");
        seriesData.put("data", number);

        Map<String, Object> series = new HashMap<>();
        series.put("type", "bar");
        series.put("name", "销售额");
        series.put("data", price);

        List<Map<String, Object>> seriesList = new ArrayList<>();
        seriesList.add(seriesData);
        seriesList.add(series);

        result.put("series", seriesList);
        return R.ok().data("options", result);
    }

    public int[] getCateNumber(int id) {
        Integer[] as = new Integer[5];
        // 宠物狗粮
        List<ProductCategories> cateList = CateService.selectByParentId(id);
        int index = 0;
        for (ProductCategories productCategory : cateList) {
            if (index < as.length) { // 确保不会超出数组 'as' 的界限
                as[index] = productCategory.getId();
                index++;
            } else {
                // 数组 'as' 已满，无法容纳更多的分类 ID。
                break; // 跳出循环
            }
        }
        // 根据分类ID 获取商品
        int number = 0;
        int price = 0;
        List<Product> productList =  productService.selectCategoriesWithParentId(as, 1, 100);
        for(Product product: productList) {
            List<Order> orderList = orderService.selectByProductId(product.getId());
            for(Order order: orderList) {
                number += order.getQuantity();
                price += order.getPrice().doubleValue();
            }
        }
        int result[] = new int[2];
        result[0] = number;
        result[1] = price;
        return result;
    }

}

